//https://www.npmjs.com/package/layaair-cmd
//消除矢量绘制的锯齿，但会增加性能消耗
//Laya.Config.isAntialias=true;
//初始化微信小游戏
Laya.MiniAdpter.init();


//公用类简写
var Text  = Laya.Text;
var Button  = Laya.Button;
var Handler = Laya.Handler;
var Sprite = Laya.Sprite;
var Event = Laya.Event;
var Tween = Laya.Tween;
var Ease = Laya.Ease;
var List = Laya.List;
var Box = Laya.Box;
var Skeleton = Laya.Skeleton;


//config
var W=600;//游戏场景宽度
var H=400;//游戏场景高度
var b_rect=20;//游戏元素单项宽高
this.frameTime=200;//定时器间隔时长
this.Tweener=null;


//程序入口
Laya.init(W, H, Laya.WebGL);//初始化
Laya.stage.bgColor="#ffffff";//游戏背景色
//适配
Laya.stage.alignH = Laya.Stage.ALIGN_CENTER;//水平对齐方式
Laya.stage.alignV = Laya.Stage.ALIGN_MIDDLE;//垂直对齐方式
//屏幕适配 缩放模式
Laya.stage.scaleMode = Laya.Stage.SCALE_SHOWALL;
//屏幕适配，横屏还是竖屏，默认不改变
Laya.stage.screenMode = Laya.Stage.SCREEN_HORIZONTAL;


//图片资源预加载 数组
var listImgs=[
	{url:"imgs/start/b.png"},
	{url:"imgs/start/title.png"},
	{url:"imgs/start/start.png"},
	{url:"imgs/start/list.png"},
	{url:"imgs/game/gameb2.png"},
	{url:"imgs/game/hl.png"},
	{url:"imgs/game/hr.png"},
	{url:"imgs/game/ht.png"},
	{url:"imgs/game/hb.png"},
	{url:"imgs/game/body.png"},
	{url:"imgs/game/food.png"},
	{url:"imgs/game/food2.png"},
	{url:"imgs/game/gameb3.png"}
];
if(Laya.Browser.window.wx){
	Laya.Browser.window.wx.showLoading({
		title: '加载中'
	})
};
//图片资源预加载
Laya.loader.load(listImgs,Handler.create(this,loaded));
//图片资源加载完成
function loaded(){	
	if(Laya.Browser.window.wx){
		Laya.Browser.window.wx.hideLoading()
	};
    //场景底图
    drawbackimg()
    //场景标题
    drawtitleimg();
	//场景开始按钮
	this.btn_s=createButton(listImgs[2].url,200,60,50,250,"开始游戏");
	//事件开始游戏
	this.btn_s.on(Event.CLICK, this, onStartGame);
	//场景排行榜按钮
	this.btn_l=createButton(listImgs[3].url,200,60,350,250,"排行榜");
	//事件显示排行榜
	this.btn_l.on(Event.CLICK, this, onShowList);
	//场景微信小游戏分享按钮
	this.btn_wxshare=createButton(listImgs[3].url,100,40,20,20,"好友分享");
	//事件微信小游戏分享
	this.btn_wxshare.on(Event.CLICK, this, onWxShare);
	
	//游戏背景图
	drawGmeBack();
	//游戏返回按钮
	this.go_back=createButton(listImgs[3].url,80,30,20,20,"返回");	
	this.go_back.visible=false;
	//游戏继续/暂停按钮
	this.go_playstop=createButton(listImgs[2].url,80,30,120,20,"暂停");	
	this.go_playstop.visible=false;
	//事件继续/暂停
	this.go_playstop.on(Event.CLICK, this, onPlayStop);
	//事件返回主界面
	this.go_back.on(Event.CLICK, this, onGoback);
	//游戏弹窗
	drawDialog();
	//游戏吃到提示
	drawsucc();
};


//场景底图
this.backimg = new Sprite();
//添加到舞台
Laya.stage.addChild(this.backimg);
function drawbackimg(){
	 this.backimg.graphics.drawTexture(Laya.loader.getRes(listImgs[0].url),0,0);
};
//场景标题
this.titleimg = new Sprite();
//添加到舞台
Laya.stage.addChild(this.titleimg);
function drawtitleimg(){
	  this.titleimg.graphics.drawTexture(Laya.loader.getRes(listImgs[1].url),150,50);
};
//场景图集动画
this.roleAni = new Laya.Animation();
// 设置播放间隔（单位：毫秒）
this.roleAni.interval = 300;	
//加载动画图集，加载成功后执行回调方法
this.roleAni.loadAtlas("imgs/ani.atlas",Laya.Handler.create(this,roleAnionLoaded));
function roleAnionLoaded(){	
	this.roleAni.pos(500,50)
	//添加到舞台
    Laya.stage.addChild(this.roleAni);
	this.roleAni.play();
	
};
//场景图集动画 播放
function roleAniplay(){
	this.roleAni.visible=true;	
	//播放动画
    this.roleAni.play();
};
//场景图集动画 停止
function roleAnistop(){
	this.roleAni.visible=false;
	//播放动画
    //this.roleAni.clear();
};
//创建按钮
function createButton(skin,width,height,x,y,label){
	var btn = new Button();
	btn.skin=skin;
	btn.labelSize=20;
	btn.label=label;
	btn.labelColors="#ffffff,#ffffff,#ffffff,#ffffff";
	btn.stateNum=3;
	btn.width=width;
	btn.height=height;
	btn.pos(x, y);
	Laya.stage.addChild(btn);
	return btn;
};
//事件显示排行榜
var ishavelist=false;
function Item(){
	//继承指针处理
	Item.__super.call(this);
	//处理
	this.size(400,100);
	this.text = new Text();
	this.addChild(this.text);
	this.img = new Sprite();
	this.addChild(this.img);
	this.setDom = function(val){
		this.text.size(300,100);
		this.text.pos(100,0);
		this.text.fontSize= 20;
		this.text.valign="middle";
		this.text.color="#ffffff";
		this.text.text = val;
		this.img.loadImage("https://www.imilive.cn/mini_program/mini_health/cd-top.png",20,20,60,60);
	};
};
//Laya.class来定义类，同时可以指定其继承关系。
Laya.class(Item, "Item", Box);
function onShowList(){
	if(!ishavelist){
		ishavelist=true;
		//绘制背景
		this.listb = new Sprite();
		this.listb.pos(100,50);
        Laya.stage.addChild(this.listb);
        //画矩形
        this.listb.graphics.drawRect(0, 0, 400, 300, "#cccccc");
		//绘制滚动列表
		let list = new List();
		this.listb.addChild(list);
		list.pos(0,0);
		list.itemRender = Item;
		list.repeatX = 1;
		list.repeatY = 3;
		// 使用但隐藏滚动条
		list.vScrollBarSkin = "";
		//数据绑定刷新回调
		list.renderHandler = new Handler(this, updateItem);
		
		// 设置数据项为对应图片的路径
		var data = [];
		for (var i = 0; i < 20; i++)
		{
			data.push("排名"+i);
		}
		list.array = data;
		//关闭按钮
		let closel=createButton(listImgs[3].url,80,30,300,0,"关闭");	
		list.addChild(closel);
		closel.on(Event.CLICK, this, function(){
			this.listb.visible=false;
		});
	}else{
		this.listb.visible=true;
	};
};
function updateItem(cell, index){
	cell.setDom(cell.dataSource);
}
//事件微信小游戏分享
function onWxShare(){
	if(Laya.Browser.window.wx){
		Laya.Browser.window.wx.shareAppMessage();
	}else{

	};
};


//事件开始游戏
function onStartGame(){
	//场景图集动画 停止
	roleAnistop();
	//画布事件监听 判断滑动方向
	Laya.stage.on(Event.MOUSE_DOWN, this, evdown);
	Laya.stage.on(Event.MOUSE_MOVE, this, evmove);
	Laya.stage.on(Event.MOUSE_UP, this, evup);
	//场景元素隐藏
	this.backimg.visible=false;
	this.titleimg.visible=false;
	this.btn_s.visible=false;
	this.btn_l.visible=false;
	this.btn_wxshare.visible=false;
	//游戏元素显示
	this.game_back.visible=true;
	this.go_back.visible=true;
	this.go_playstop.visible=true;
	//绘制蛇
	Snake();
	//绘制食物
	Food(true);
	//移动
	move();	
};
//移动
function move(){
	//定时器清除
	clearInterval(this.time);
	//定时器
	this.timer=setInterval(()=>{
		let next_xy=null;
		if(this.direction=="left"){
			next_xy={x:this.snake_arr[0].x-1,y:this.snake_arr[0].y};
		}else if(this.direction=="right"){
			next_xy={x:this.snake_arr[0].x+1,y:this.snake_arr[0].y};
		}else if(this.direction=="top"){
			next_xy={x:this.snake_arr[0].x,y:this.snake_arr[0].y-1};
		}else if(this.direction=="bottom"){
			next_xy={x:this.snake_arr[0].x,y:this.snake_arr[0].y+1};
		};
		//判断是否死亡
		if(next_xy.x<0 || next_xy.x>=W/b_rect || next_xy.y<0 || next_xy.y>=H/b_rect){
			//死亡
			death();
			return false;
		};
		//吃到食物
		if(next_xy.x == this.food.cx && next_xy.y == this.food.cy){
			this.snake_arr.unshift({
				x:next_xy.x,
				y:next_xy.y
			});
			//绘制蛇
			Snake();
			//绘制食物
			Food(true);
			//吃到提示
			drawsuccshow(next_xy.x,next_xy.y);
			clearTimeout(this.timerSucc);
			this.timerSucc=setTimeout(()=>{
				drawsucchide();
			},500)
			return false;
		};
		//正常游走
		for(var i=this.snake_arr.length-1;i>=1;i--){
			this.snake_arr[i]=this.snake_arr[i-1]
		};		
		this.snake_arr[0]={
			x:next_xy.x,
			y:next_xy.y
		};
		//绘制蛇
		Snake()
	},this.frameTime);
};
//画布事件监听 判断滑动方向
function evdown(){
	this.prevX = Laya.stage.mouseX;
    this.prevY = Laya.stage.mouseY;
};
function evmove(){

};
function evup(){
	let distanceX=Laya.stage.mouseX-this.prevX;
	let distanceY=Laya.stage.mouseY-this.prevY;
    if(Math.abs(distanceX)>Math.abs(distanceY) && Laya.stage.mouseX<this.prevX){
		//console.log("向左滑动") 
		if(this.direction=="right"){
			return false;
		}
		//方向
		this.direction="left";
    };
    if(Math.abs(distanceX)>Math.abs(distanceY) && Laya.stage.mouseX>this.prevX){
      	//console.log("向右滑动")
		if(this.direction=="left"){
			return false;
		}
		//方向
		this.direction="right";
    };
	if(Math.abs(distanceX)<Math.abs(distanceY) && Laya.stage.mouseY<prevY){
      	//console.log("向上滑动") 
		if(this.direction=="bottom"){
			return false;
		}
		//方向
		this.direction="top";
    };
	if(Math.abs(distanceX)<Math.abs(distanceY) && Laya.stage.mouseY>prevY){
      	//console.log("向下滑动") 
		if(this.direction=="top"){
			return false;
		}
		//方向
		this.direction="bottom";
    };
	this.prevX = Laya.stage.mouseX;
    this.prevY = Laya.stage.mouseY;
};


//绘制游戏背景图

this.game_back = new Sprite();	
Laya.stage.addChild(this.game_back);
function drawGmeBack(){
	this.game_back.visible=false;
	for(var j=0;j<H/b_rect;j++){
		for(var i=0;i<W/b_rect;i++){

			this.game_back.graphics.drawTexture(Laya.loader.getRes(listImgs[4].url),i*b_rect,j*b_rect);
		
		};
	};
};
//绘制食物
this.food = new Sprite();
Laya.stage.addChild(this.food);
function Food(is){
	this.food.graphics.clear();	
	this.food.visible=is;
	//出现的随机位置
	let rx= Math.floor(Math.random()*W/b_rect);
	let ry= Math.floor(Math.random()*H/b_rect);
	//记录随机位置
	this.food.cx=rx;
	this.food.cy=ry;
	this.food.graphics.drawTexture(Laya.loader.getRes(listImgs[10].url),rx*b_rect,ry*b_rect);
};
//绘制蛇
this.snake_arr=[
	{x:15,y:10},
	{x:15,y:11},
	{x:15,y:12}
];
//方向
this.direction="top";
//定时器
this.timer=null;
this.snake = new Sprite();
Laya.stage.addChild(this.snake);
function Snake(){	
	this.snake.graphics.clear();	
	for(var i=0;i<this.snake_arr.length;i++){
		if(i==0){
			if(this.direction=="left"){
				this.snake.graphics.drawTexture(Laya.loader.getRes(listImgs[5].url),this.snake_arr[i].x*b_rect,this.snake_arr[i].y*b_rect);
			}else if(this.direction=="right"){
				this.snake.graphics.drawTexture(Laya.loader.getRes(listImgs[6].url),this.snake_arr[i].x*b_rect,this.snake_arr[i].y*b_rect);
			}else if(this.direction=="top"){
				this.snake.graphics.drawTexture(Laya.loader.getRes(listImgs[7].url),this.snake_arr[i].x*b_rect,this.snake_arr[i].y*b_rect);
			}else if(this.direction=="bottom"){
				this.snake.graphics.drawTexture(Laya.loader.getRes(listImgs[8].url),this.snake_arr[i].x*b_rect,this.snake_arr[i].y*b_rect);
			};
		}else{
			this.snake.graphics.drawTexture(Laya.loader.getRes(listImgs[9].url),this.snake_arr[i].x*b_rect,this.snake_arr[i].y*b_rect);
		};
	};
};
//重新开始弹窗
this.dialog = new Sprite();
Laya.stage.addChild(this.dialog);
function drawDialog(){
	this.dialog.y=-400;
	//自定义路径
	var path =  [
		["moveTo", 30, 0], //画笔的起始点，
		["lineTo", 370, 0],
		["arcTo", 400, 0, 400, 30, 30], //p1（500,0）为夹角B，（500,30）为端点p2
		["lineTo", 400, 170],
		["arcTo", 400, 200, 370, 200, 30],//p1（500,300）为夹角C，（470,300）为端点p2
		["lineTo", 30, 200],
		["arcTo", 0, 200, 0, 170, 30], //p1(0,300)为夹角D，（0,270）为端点p2
		["lineTo", 0, 30],
		["arcTo", 0, 0, 30, 0, 30],//p1(0,0)为夹角A，（30,0）为端点p2
		["lineTo", 30, 0]
	];
	//绘制圆角矩形
	this.dialog.graphics.drawPath(100, 100, path, {fillStyle: "#00caff"});
	//弹窗描述
	var txt = new Text();
	//设置文本内容
	txt.text = "已经死亡，可以点击重新游戏";
	//设置文本颜色
	txt.color = "#ffffff";
	txt.width = 400;
	txt.height = 80;
	txt.align="center";
	txt.valign="middle";
	txt.fontSize=20;
	txt.pos(100,100);
	this.dialog.addChild(txt);
	//事件重新开始
	this.btn_rg=createButton(listImgs[2].url,200,60,200,200,"重新开始");
	this.dialog.addChild(this.btn_rg);
	this.btn_rg.on(Event.CLICK, this, onreGame);
};


//重置蛇
function resetSnake(){
	//定时器清除
	clearInterval(this.timer);
	//绘制蛇
	this.snake_arr=[
		{x:15,y:10},
		{x:15,y:11},
		{x:15,y:12}
	];
	//方向
	this.direction="top";
	this.snake.graphics.clear();
};
//事件返回主界面
function onGoback(){
	//场景图集动画 停止
	roleAniplay();
	//场景元素显示
	this.backimg.visible=true;
	this.titleimg.visible=true;
	this.btn_s.visible=true;
	this.btn_l.visible=true;
	this.btn_wxshare.visible=true;
	//游戏元素隐藏
	this.game_back.visible=false;
	this.go_back.visible=false;
	this.go_playstop.visible=false;
	this.go_playstop.label="暂停";
	//重置蛇
	resetSnake();
	//画布事件监听 判断滑动方向
	Laya.stage.off(Event.MOUSE_DOWN, this, evdown);
	Laya.stage.off(Event.MOUSE_MOVE, this, evmove);
	Laya.stage.off(Event.MOUSE_UP, this, evup);
	//绘制食物
	Food(false);
	//重新开始弹窗
	this.dialog.y=-400;
	//弹窗动画清除
	this.Tweener?this.Tweener.clear():null;
};
//死亡
function death(){
	//动画定时器清除
	clearInterval(this.timer);
	//重新开始弹窗
	this.Tweener=Laya.Tween.to(this.dialog,{y:0},500,Laya.Ease.elasticInOut,null,0);
};
//游戏吃到提示
this.foodsucc = new Sprite();
Laya.stage.addChild(this.foodsucc);
function drawsucc(){
	this.foodsucc.visible=false;
	this.foodsucc.graphics.drawTexture(Laya.loader.getRes(listImgs[11].url),0,0);
};
function drawsuccshow(x,y){
	this.foodsucc.visible=true;	
	this.foodsucc.graphics.clear();
	this.foodsucc.graphics.drawTexture(Laya.loader.getRes(listImgs[11].url),x*b_rect,y*b_rect);	
};
function drawsucchide(){
	this.foodsucc.visible=false;
};
//事件重新开始
function onreGame(){
	//重新开始弹窗
	this.Tweener=Laya.Tween.to(this.dialog,{y:-400},500,Laya.Ease.elasticInOut,null,0);
	//重置蛇
	resetSnake();
	this.go_playstop.label="暂停";
	//绘制蛇
	Snake();
	//绘制食物
	Food(true);
	//移动
	move();	
};
//事件继续/暂停
function onPlayStop(){
	if(this.go_playstop.label=="暂停"){
		this.go_playstop.label="继续";
		//动画定时器清除
		clearInterval(this.timer);
	}else if(this.go_playstop.label=="继续"){
		this.go_playstop.label="暂停";
		//移动
		move();	
	};
};